<template>
  <div class="container">
    <div class="form-container">
      <h2>原料管理</h2>
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="原料ID" prop="id">
          <el-input-number
            v-model="form.id"
            :min="1"
            :precision="0"
            controls-position="right"
            placeholder="请输入ID"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="长度(mm)" prop="length">
          <el-input-number
            v-model="form.length"
            :min="0.01"
            :precision="2"
            :step="0.1"
            placeholder="请输入长度"
          ></el-input-number>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmit('add')"
            :loading="loading.add"
          >新增</el-button>
          <el-button 
            type="danger" 
            @click="handleSubmit('delete')"
            :loading="loading.delete"
          >删除</el-button>
          <el-button 
            type="warning" 
            @click="handleSubmit('update')"
            :loading="loading.update"
          >更新</el-button>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>
      
      <el-table :data="rawMaterials" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="120" sortable></el-table-column>
        <el-table-column prop="length" label="长度(mm)" width="150">
          <template #default="{row}">
            {{ Number(row.length).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button size="small" @click="editRaw(row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleRowDelete(row)"
              :loading="loading.delete === row.id"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const api = axios.create({
  baseURL: '/oneDimension',
  headers: {
    'Content-Type': 'application/json'
  }
})

// 响应式数据
const form = reactive({
  id: null,
  length: null
})

const rawMaterials = ref([])
const loading = reactive({
  add: false,
  delete: false,
  update: false
})

// 表单验证规则（严格匹配OpenAPI规范）
const rules = {
  id: [
    { required: true, message: '必填项', trigger: 'blur' },
    { 
      validator: (_, v) => Number.isInteger(v) && v > 0,
      message: '必须为正整数',
      trigger: 'blur'
    }
  ],
  length: [
    { required: true, message: '必填项', trigger: 'blur' },
    { 
      validator: (_, v) => v > 0,
      message: '必须大于0',
      trigger: 'blur'
    }
  ]
}

// // 加载原料数据
// const loadRawMaterials = async () => {
//   try {
//     const { data } = await api.get('/raw/list') // 假设后端已实现该接口
//     if (data.code === 200) {
//       rawMaterials.value = data.data.map(item => ({
//         id: item.id,
//         length: Number(item.length)
//       }))
//     }
//   } catch (error) {
//     handleError(error)
//   }
// }

// 统一操作处理（修复case作用域问题）
const handleSubmit = async (action) => {
  try {
    await formRef.value.validate()
    loading[action] = true
    
    // 构造符合OpenAPI规范的请求体
    const payload = {
      id: Number(form.id),
      length: Number(form.length)
    }

    let response
    switch(action) {
      case 'add': {
        response = await api.post('/raw/add', payload)
        rawMaterials.value.push({...payload})
        break
      }
      case 'delete': {
        response = await api.delete('/raw/delete', { data: payload })
        rawMaterials.value = rawMaterials.value.filter(item => item.id !== payload.id)
        break
      }
      case 'update': {
        response = await api.put('/raw/update', payload)
        const index = rawMaterials.value.findIndex(item => item.id === payload.id)
        if (index !== -1) rawMaterials.value.splice(index, 1, {...payload})
        break
      }
    }

    if (response.data.code === 200) {
      ElMessage.success(`${actionMap[action]}成功`)
      if (action === 'add') resetForm()
    } else {
      ElMessage.error(response.data.msg || `${actionMap[action]}失败`)
    }
  } catch (error) {
    handleError(error)
  } finally {
    loading[action] = false
  }
}

// 行删除操作（单独处理）
const handleRowDelete = async (row) => {
  try {
    loading.delete = row.id
    
    // 构造符合OpenAPI规范的请求体
    const payload = {
      id: row.id,
      length: row.length
    }

    const response = await api.delete('/raw/delete', { data: payload })
    if (response.data.code === 200) {
      rawMaterials.value = rawMaterials.value.filter(item => item.id !== row.id)
      ElMessage.success('删除成功')
    }
  } catch (error) {
    handleError(error)
  } finally {
    loading.delete = null
  }
}

// 编辑原料
const editRaw = (row) => {
  form.id = row.id
  form.length = row.length
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
}

// 统一错误处理
const handleError = (error) => {
  const message = error.response?.data?.msg || 
                 error.message || 
                 '请求失败，请检查：\n1. 后端服务状态\n2. 网络连接\n3. 代理配置'
  ElMessage.error(message)
  console.error('API错误:', error)
}

// 操作映射
const actionMap = {
  add: '新增',
  delete: '删除',
  update: '更新'
}

// // 初始化加载数据
// onMounted(() => {
//   loadRawMaterials()
// })

const formRef = ref(null)
</script>

<style scoped>
.container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.form-container {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.el-input-number {
  width: 100%;
}

.el-table {
  margin-top: 24px;
}

.el-divider {
  margin: 24px 0;
}

.el-button + .el-button {
  margin-left: 12px;
}
</style>